package guiservice.simulator;

import guiservice.server.logic.ControlsManager;
import lombok.extern.log4j.Log4j;

import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.JPanel;

@Log4j
public class DrawablePanel extends JPanel {

    public DrawablePanel() {
        ControlsManager.getInstance().setBoard(this);
        requestFocus();
        addMouseListener(new MouseListener() {

            @Override
            public void mousePressed(MouseEvent evt) {
                ControlsManager.getInstance().onMouseDownHandler(evt.getX(), evt.getY());
            }

            @Override
            public void mouseReleased(MouseEvent evt) {
                ControlsManager.getInstance().onMouseUpHandler(evt.getX(), evt.getY());
            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }

            @Override
            public void mouseClicked(MouseEvent evt) {
                ControlsManager.getInstance().onMouseClickedHandler(evt.getX(), evt.getY());
            }
        });
        addMouseMotionListener(new MouseMotionListener() {
            @Override
            public void mouseDragged(MouseEvent e) {

            }

            @Override
            public void mouseMoved(MouseEvent e) {
                ControlsManager.getInstance().onMouseMovedHandler(e.getX(), e.getY());
            }
        });
        addMouseWheelListener(new MouseWheelListener() {
            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
                    ControlsManager.getInstance().onScrollHandler(e.getX(), e.getY(), e.getWheelRotation());
                }
            }
        });

        addKeyListener(keyListener);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        ControlsManager.getInstance().redraw(g);
    }

    private static KeyListener keyListener = new java.awt.event.KeyListener() {

        @Override
        public void keyTyped(KeyEvent evt) {

        }

        @Override
        public void keyPressed(KeyEvent evt) {
            ControlsManager.getInstance().onKeyPressed(
                    KeyEvent.getKeyText(evt.getKeyCode()), KeyEvent.getKeyModifiersText(evt.getModifiers()));
        }

        @Override
        public void keyReleased(KeyEvent evt) {
            ControlsManager.getInstance().onKeyReleased(
                    KeyEvent.getKeyText(evt.getKeyCode()), KeyEvent.getKeyModifiersText(evt.getModifiers()));
        }
    };

    public static KeyListener GetKeyListener() {
        return keyListener;
    }
}
